package com.fish.gaiety.gateway.configuration;

import com.fish.gaiety.gateway.base.GenericResponseBody;
import com.fish.gaiety.gateway.base.ResponseApi;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

@RestControllerAdvice
public class GenericResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        var annotationFlag =
                Objects.requireNonNull(returnType.getMethod())
                        .getAnnotation(GenericResponseBody.class);
        return !ObjectUtils.isEmpty(annotationFlag);
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        var annotationFlag =
                Objects.requireNonNull(returnType.getMethod())
                        .getAnnotation(GenericResponseBody.class);

        return ResponseApi
                        .status(annotationFlag.success())
                        .body(body);
    }
}
